<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 系统操作日志添加方法
 * string $type 操作平台：1 系统后台
 * string $play_type 操作类型：1 添加  2 编辑  3查看  4 删除  5登录  6导入  7导出
 * string $content 操作说明
 * string $uid 操作者id
 * @author liushiwei
 * 2017-9-7 17:35:04
 */
function add_system_log( $uid=0, $type=1, $play_type=1, $content='', $sid=0 ) {
    //添加内容
    $data               = [];
    $data['uid']        = $uid ? $uid : 0;
    $data['sid']        = $sid ? $sid : 0;
    $data['ip_address'] = get_client_ip();
    $data['type']       = $type;
    $data['play_type']  = $play_type;
    $data['url']        = $_SERVER['REQUEST_URI'];//当前操作url
    $data['content']    = $content;
    $data['ctime']      = time();
    
    //添加日志
    //model( 'system_log' )->addData( $data );
    db('system_log')->insertGetId($data);
}
/**
 * 获取客户端IP地址
 */
function get_client_ip( $type=0 ) {
    global $ip; 
    if( getenv( "HTTP_CLIENT_IP" ) ) {
        $ip = getenv( "HTTP_CLIENT_IP" );
    } else if( getenv( "HTTP_X_FORWARDED_FOR" ) ) {
        $ip = getenv( "HTTP_X_FORWARDED_FOR" );
    } else if( getenv( "REMOTE_ADDR" ) ) {
        $ip = getenv( "REMOTE_ADDR" );
    } else {
        $ip = "0.0.0.0";
    }
    // IP地址合法验证
    $long = sprintf( "%u", ip2long( $ip ) );
    $ip   = $long ? array($ip, $long) : array( '0.0.0.0', 0 );
    return $ip[$type];
}
/**
 * 把返回的数据集转换成Tree
 * @param array $list 要转换的数据集
 * @param string $pid parent标记字段
 * @param string $level level标记字段
 * @return array
 */
function list_to_tree( $list, $pk='id', $pid = 'pid', $child = '_child', $root = 0) {
    // 创建Tree
    $tree = [];
    if( is_array( $list ) ) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] =& $list[$key];
        }
        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId =  $data[$pid];
            if ($root == $parentId) {
                $tree[] =& $list[$key];
            }else{
                if (isset($refer[$parentId])) {
                    $parent =& $refer[$parentId];
                    $parent[$child][] =& $list[$key];
                }
            }
        }
    }
    return $tree;
}